package cn.itcast.flink.examples;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.AggregateOperator;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;

/**
 * Author itcast
 * Date 2022/1/10 17:38
 * Desc TODO
 */
public class WordCountBatch {
    public static void main(String[] args) throws Exception {
        //创建批环境
        ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
        //1.读取数据
        DataSource<String> source = env.readTextFile("D:\\project\\flinkbase27\\data\\words.txt");
        //2.转换数据
        AggregateOperator<Tuple2<String, Integer>> result = source.flatMap(new FlatMapFunction<String, String>() {
            @Override
            public void flatMap(String value, Collector<String> out) throws Exception {
                String[] words = value.split(" ");
                for (String word : words) {
                    out.collect(word);
                }
            }
        }).map(new MapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public Tuple2<String, Integer> map(String value) throws Exception {
                return Tuple2.of(value, 1);
            }
        }).groupBy(0)
          .sum(1);
        //3.打印输出
        result.print();
    }
}
